<?php
namespace apps\admin\controller;
use apps\common\controller\Backend;

class Admins extends Backend
{
	/**
	 * 管理员列表
	 */
    public function index()
    {
        if(is_ajax()){
			$where = [];
			$uname = input('username');
			if(!empty($uname)) $where['username'] = ['like','%'.$uname.'%'];

			$email = input('email');
			if(!empty($email)) $where['email'] = ['like','%'.$email.'%'];

			$role_id = input('role_id'); 
			if(!empty($role_id)) $where['role_id'] = $role_id;

			$user = db('admin')->alias('t')->field('t.*,b.title as role')->join('admin_role b','b.role_id=t.role_id')->where($where)->select();      
            return $this->renderSuccess($user);
        }
        
	    $role = db('admin_role')->where(['status'=>1])->select();
	    return $this->fetch('index',['roles'=>$role]);
	}
	/**
	 * 删除管理员
	 */
	public function del(){
		if(is_ajax()){			
			$user_id = input('user_id');
			$exits = db('admin')->where("user_id IN ({$user_id})")->delete();
			if($exits){
				return $this->renderSuccess([],'删除成功');
			}
			return $this->renderError('删除失败');
		}
	}

	/**
	 * 编辑管理员
	 */
	public function edit(){
		if(is_ajax()){
			$user_id = input('user_id');
			$uname = input('username');
	        $exits = db('admin')->where("username='{$uname}' and user_id<>'{$user_id}'")->find();
	        if($exits){
	            return $this->renderError('该登录名已经存在；请更换');
	        }
	        $data = [
	            'username' => input('username'),
	            'password' => input('password','','trim,md5'),
	            'email' => input('email'),
	            'real_name' => input('real_name'),
	            'role_id' => input('role_id'),
	            'status' => input('status')=='on'?1:0,
	        ];
	        $ret = db('admin')->where("user_id='{$user_id}'")->update($data);
	        if($ret){
	            return $this->renderSuccess([],'保存成功');
	        }
	        return $this->renderError('保存失败');
		}		 
		$user = db('admin')->where(['user_id'=>input('user_id')])->find();  
		$role = db('admin_role')->where(['status'=>1])->select();
		return $this->fetch('edit',[ 'admin'=>$user, 'roles'=>$role ]);
	}
	
	/**
	 * 添加管理员用户
	 */
	public function add(){
	    if(is_ajax()){
	        
	        $exits = db('admin')->where(['username'=>input('username')])->find();
	        if($exits){
	            return $this->renderError('该登录名已经存在；请更换');
	        }
	        $data = [
	            'username' => input('username'),
	            'password' => input('password','','trim,md5'),
	            'email' => input('email'),
	            'real_name' => input('real_name'),
	            'role_id' => input('role_id'),
	            'status' => input('status')=='on'?1:0,
	        ];
	        $ret = db('admin')->insert($data);
	        if($ret){
	            return $this->renderSuccess([],'保存成功');
	        }
	        return $this->renderError('保存失败');
	    }
	    $role = db('admin_role')->where(['status'=>1])->select();
	    return $this->fetch('add',['roles'=>$role]);
	}
}
